const prisma = require('../config/database');
const formatDateTime = require('../utils/formatDateTime');

// 根据用户ID分页获取复查任务列表
exports.getAssignmentList = async (req, res) => {
  try {
    const { userId, status = '所有状态', page = 1, pageSize = 10 } = req.query;

    // 参数验证
    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: userId'
      });
    }

    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const take = parseInt(pageSize);

    // 构建查询条件
    const whereClause = {
      checker_id: parseInt(userId)
    };

    // 如果status不是"所有状态"，则添加status条件
    if (status !== '所有状态') {
      const parsedStatus = parseInt(status);
      whereClause.recheck_status = parsedStatus;
    }

    // 查询符合条件的复查任务
    const recheckTasks = await prisma.recheck.findMany({
      where: whereClause,
      orderBy: {
        assign_time: 'desc' // 按分配时间降序排列
      },
      skip,
      take
    });

    // 获取总数
    const total = await prisma.recheck.count({
      where: whereClause
    });

    // 获取查卷申请信息，学生试卷信息和考试信息
    const list = await Promise.all(recheckTasks.map(async (task) => {
      // 获取查卷申请信息
      const recheckRequest = await prisma.recheck_request.findFirst({
        where: { id: task.recheck_request_id }
      });

      let studentName = '未知学生';
      let examinationName = '未知考试';

      if (recheckRequest) {
        // 获取学生试卷信息
        const studentPaper = await prisma.student_paper.findFirst({
          where: { id: recheckRequest.student_paper_id }
        });

        if (studentPaper) {
          // 获取学生信息
          const student = await prisma.user.findUnique({
            where: { id: studentPaper.user_id }
          });

          if (student) {
            studentName = student.name || '未知学生';
          }

          // 获取考试信息
          const examination = await prisma.examination.findUnique({
            where: { id: studentPaper.examination_id }
          });

          if (examination) {
            examinationName = examination.name || '未知考试';
          }
        }
      }

      return {
        recheckId: task.id,
        recheckRequestId: task.recheck_request_id,
        assignTime: formatDateTime(task.assign_time),
        recheckStatus: task.recheck_status,
        totalScore: task.total_score || 0,
        studentName,
        examinationName
      };
    }));

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        list,
        total
      }
    });
  } catch (error) {
    console.error('获取复查任务列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取复查任务列表失败: ' + error.message
    });
  }
};

// 根据复审ID修改复审记录
exports.updateTheRecheck = async (req, res) => {
  try {
    const { recheckId, status } = req.body;
    
    // 参数验证
    if (!recheckId || status === undefined) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckId, status'
      });
    }

    // 查询复审记录是否存在
    const existingRecheck = await prisma.recheck.findUnique({
      where: { id: parseInt(recheckId) }
    });

    if (!existingRecheck) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '复审记录不存在'
      });
    }

    // 更新复审记录
    await prisma.recheck.update({
      where: { id: parseInt(recheckId) },
      data: {
        recheck_status: parseInt(status)
      }
    });

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
    
  } catch (error) {
    console.error('修改复审记录失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '修改复审记录失败: ' + error.message
    });
  }
};

// 获取学生的试卷详情(复审批阅详情)
exports.getRecheckPaperDetails = async (req, res) => {
  try {
    const { recheckId } = req.query;
    
    // 参数验证
    if (!recheckId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckId'
      });
    }

    // 查询复审记录
    const recheck = await prisma.recheck.findUnique({
      where: { id: parseInt(recheckId) }
    });

    if (!recheck) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '复审记录不存在'
      });
    }

    // 获取复审查卷申请
    const recheckRequest = await prisma.recheck_request.findUnique({
      where: { id: recheck.recheck_request_id }
    });

    if (!recheckRequest) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '查卷申请不存在'
      });
    }

    // 获取学生试卷
    const studentPaper = await prisma.student_paper.findUnique({
      where: { id: recheckRequest.student_paper_id }
    });

    if (!studentPaper) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生试卷不存在'
      });
    }

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: studentPaper.examination_id }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '考试不存在'
      });
    }

    // 获取学生信息
    const student = await prisma.user.findUnique({
      where: { id: studentPaper.user_id }
    });

    if (!student) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生不存在'
      });
    }

    // 获取学生班级
    const studentClass = await prisma.student_classes.findFirst({
      where: { student_id: student.id }
    });

    let classesName = '未知班级';
    if (studentClass) {
      const classInfo = await prisma.classes.findUnique({
        where: { id: studentClass.classes_id }
      });
      classesName = classInfo ? classInfo.name : '未知班级';
    }

    // 获取试卷的满分（考试计划中所有题目的总分）
    let paperFullMark = 0;
    if (examination.exam_plan_id) {
      const examPlanDetails = await prisma.exam_plan_details.findMany({
        where: { exam_plan_id: examination.exam_plan_id }
      });
      paperFullMark = examPlanDetails.reduce((total, detail) => total + (detail.score || 0), 0);
    }

    // 获取复审详情
    const recheckDetails = await prisma.recheck_detail.findMany({
      where: { recheck_id: parseInt(recheckId) },
      orderBy: { id: 'asc' }
    });

    // 获取总数和已完成数量
    const total = recheckDetails.length;
    const doneTotal = recheckDetails.filter(detail => detail.status === 1).length;

    // 获取试卷详情
    const paperDetails = await prisma.paper_detail.findMany({
      where: { student_paper_id: studentPaper.id },
      orderBy: { question_order: 'asc' }
    });

    // 创建试卷详情ID到对象的映射
    const paperDetailMap = {};
    paperDetails.forEach(detail => {
      paperDetailMap[detail.id] = detail;
    });

    // 获取所有题目ID
    const questionIds = paperDetails.map(detail => detail.question_id);

    // 获取所有题目信息
    const questions = await prisma.question.findMany({
      where: { id: { in: questionIds } }
    });

    // 创建题目ID到对象的映射
    const questionMap = {};
    questions.forEach(question => {
      questionMap[question.id] = question;
    });

    // 获取所有批改教师的ID
    const teacherIds = paperDetails.filter(detail => detail.user_id).map(detail => detail.user_id);

    // 获取教师信息
    const teachers = await prisma.user.findMany({
      where: { id: { in: teacherIds } }
    });

    // 创建教师ID到名称的映射
    const teacherMap = {};
    teachers.forEach(teacher => {
      teacherMap[teacher.id] = teacher.name;
    });

    // 获取所有答案信息
    const answerIds = questions.map(q => q.answer_id).filter(id => id !== null);

    // 获取主观题答案
    const subjectiveAnswers = await prisma.subjective_answers.findMany({
      where: { id: { in: answerIds } }
    });
    
    // 获取客观题答案
    const objectiveAnswers = await prisma.objective_answers.findMany({
      where: { id: { in: answerIds } }
    });
    
    // 创建答案ID到信息的映射
    const answerMap = {};
    subjectiveAnswers.forEach(answer => {
      answerMap[`subjective_${answer.id}`] = answer;
    });
    objectiveAnswers.forEach(answer => {
      answerMap[`objective_${answer.id}`] = answer;
    });

    // 整理主观题和客观题数据
    const subjective = [];
    const objective = [];

    // 遍历复审详情并组织数据
    for (const recheckDetail of recheckDetails) {
      const paperDetail = paperDetailMap[recheckDetail.paper_detail_id];
      if (!paperDetail) continue;

      const question = questionMap[paperDetail.question_id];
      if (!question) continue;

      // 获取大题信息
      const bigQuestion = await prisma.big_question.findUnique({
        where: { id: paperDetail.big_question_id }
      });

      // 处理question_content，尝试将JSON字符串转换为对象
      let processedQuestionContent = question.question_content;
      try {
        if (question.question_content && typeof question.question_content === 'string' && 
            (question.question_content.startsWith('{') || question.question_content.startsWith('['))) {
          processedQuestionContent = JSON.parse(question.question_content);
        }
      } catch (error) {
        console.warn('解析题目内容JSON失败:', error);
        // 解析失败时保持原始内容
      }

      // 获取题目分数
      let score = 0;
      if (bigQuestion && examination.exam_plan_id) {
        const examPlanDetail = await prisma.exam_plan_details.findFirst({
          where: {
            exam_plan_id: examination.exam_plan_id,
            big_question_id: bigQuestion.id,
            question_order: paperDetail.question_order
          }
        });
        score = examPlanDetail ? (examPlanDetail.score || 0) : 0;
      }

      const baseInfo = {
        recheckId: parseInt(recheckId),
        recheckDetailId: recheckDetail.id,
        questionOrder: paperDetail.question_order,
        questionId: paperDetail.question_id,
        questionName: question.name,
        questionContent: processedQuestionContent,
        studentAnswer: paperDetail.student_answer,
        score: score,
        finalScore: paperDetail.final_score || 0,
        recheckDetailFinalScore: recheckDetail.final_score || 0,
        status: recheckDetail.status || 0
      };

      // 判断是客观题还是主观题
      if (question.answer_type_id === 1) { // 客观题
        const answer = answerMap[`objective_${question.answer_id}`];
        objective.push({
          ...baseInfo,
          questionAnswer: answer ? answer.question_answer : ''
        });
      } else if (question.answer_type_id === 2) { // 主观题
        const answer = answerMap[`subjective_${question.answer_id}`];
        
        // 处理评分细则，将分隔符"|"的字符串转换为数组
        let gradingRulesArray = [];
        if (answer && answer.grading_rules) {
          gradingRulesArray = answer.grading_rules.split('|').filter(rule => rule.trim() !== '');
        }
        
        subjective.push({
          ...baseInfo,
          checkDerail: paperDetail.check_detail || '',
          userId: paperDetail.user_id,
          userName: paperDetail.user_id ? (teacherMap[paperDetail.user_id] || '未知教师') : '',
          referenceAnswer: answer ? answer.reference_answer : '',
          gradingRules: gradingRulesArray
        });
      }
    }

    // 对subjective和objective数组按照question_order升序排列
    subjective.sort((a, b) => a.questionOrder - b.questionOrder);
    objective.sort((a, b) => a.questionOrder - b.questionOrder);

    // 组装返回数据
    const result = {
      total,
      doneTotal,
      recheckStatus: recheck.recheck_status,
      examinationData: {
        name: examination.name,
        startTime: formatDateTime(examination.start_time),
        endTime: formatDateTime(examination.end_time),
        paperFullMark
      },
      studentData: {
        name: student.name,
        account: student.account,
        classesName,
        totalScore: studentPaper.total_score || 0
      },
      subjective,
      objective
    };

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: result
    });
    
  } catch (error) {
    console.error('获取复审批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取复审批阅详情失败: ' + error.message
    });
  }
};

// 保存复审批阅详情
exports.saveRecheck = async (req, res) => {
  try {
    const { recheckDetailId, recheckDetailFinalScore } = req.body;
    
    // 参数验证
    if (!recheckDetailId || recheckDetailFinalScore === undefined) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckDetailId, recheckDetailFinalScore'
      });
    }

    // 查询复审详情记录是否存在
    const existingRecheckDetail = await prisma.recheck_detail.findUnique({
      where: { id: parseInt(recheckDetailId) }
    });

    if (!existingRecheckDetail) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '复审详情记录不存在'
      });
    }

    // 更新复审详情记录
    await prisma.recheck_detail.update({
      where: { id: parseInt(recheckDetailId) },
      data: {
        final_score: parseFloat(recheckDetailFinalScore),
        status: 1 // 已批阅
      }
    });

   

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
    
  } catch (error) {
    console.error('保存复审批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '保存复审批阅详情失败: ' + error.message
    });
  }
};

// 提交全部复审
exports.handleRecheck = async (req, res) => {
  try {
    const { recheckRequestId, recheckId } = req.body;
    
    // 参数验证
    if (!recheckRequestId || !recheckId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckRequestId, recheckId'
      });
    }

    // 查询复审记录是否存在
    const existingRecheck = await prisma.recheck.findUnique({
      where: { id: parseInt(recheckId) }
    });

    if (!existingRecheck) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '复审记录不存在'
      });
    }

    // 获取该复审下的所有复审详情记录
    const recheckDetails = await prisma.recheck_detail.findMany({
      where: { recheck_id: parseInt(recheckId) }
    });

    // 检查是否所有复审详情都已完成批阅
    const allReviewed = recheckDetails.every(detail => detail.status === 1);
    
    if (!allReviewed) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '还有未完成批阅的复审详情，无法提交'
      });
    }

    // 计算总分
    const totalScore = recheckDetails.reduce((sum, detail) => sum + (detail.final_score || 0), 0);
    
    // 创建东八区当前时间
    const now = new Date();
    const utc8Date = new Date(now.getTime() + (8 * 60 * 60 * 1000));

    // 更新复审记录
    await prisma.recheck.update({
      where: { id: parseInt(recheckId) },
      data: {
        recheck_status: 2, // 已审核
        total_score: totalScore,
        recheck_time: utc8Date
      }
    });

    // 检查查卷申请下的所有复审记录是否都已完成
    const allRechecks = await prisma.recheck.findMany({
      where: { recheck_request_id: parseInt(recheckRequestId) }
    });

    const allRechecksCompleted = allRechecks.every(recheck => recheck.recheck_status === 2);

    // 如果所有复审记录都已完成，更新查卷申请状态
    if (allRechecksCompleted) {
      // 计算所有复审记录的平均分
      const totalScoreSum = allRechecks.reduce((sum, recheck) => sum + (recheck.total_score || 0), 0);
      const averageScore = totalScoreSum / allRechecks.length;

      // 获取查卷申请信息
      const recheckRequest = await prisma.recheck_request.findUnique({
        where: { id: parseInt(recheckRequestId) }
      });

      // 检查分数是否变更
      const isScoreChanged = recheckRequest && Math.abs(recheckRequest.original_score - averageScore) > 0.01 ? 1 : 0;

      // 更新查卷申请记录
      await prisma.recheck_request.update({
        where: { id: parseInt(recheckRequestId) },
        data: {
          status: 2, // 已完成
          final_score: averageScore,
          is_score_changed: isScoreChanged,
          process_time: utc8Date
        }
      });

      // 如果分数变更，则需要更新学生试卷的总分
      if (isScoreChanged && recheckRequest) {
        await prisma.student_paper.update({
          where: { id: recheckRequest.student_paper_id },
          data: {
            total_score: averageScore
          }
        });
      }
    }

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
    
  } catch (error) {
    console.error('提交复审失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '提交复审失败: ' + error.message
    });
  }
};
